package mo.tags.recursion;

import mo.common.ListNode;

public class L2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        int carry = 0;
        while (l1 != null && l2 != null) {
            int val = (l1.val + l2.val + carry) % 10;
            carry = (l1.val + l2.val + carry) / 10;
            ListNode tmp = new ListNode(val);
            cur.next = tmp;
            cur = tmp;
            l1 = l1.next;
            l2 = l2.next;
        }
        ListNode left = (l1 == null) ? l2 : l1;
        while (left != null) {
            int val = (left.val + carry) % 10;
            carry = (left.val + carry) / 10;
            ListNode tmp = new ListNode(val);
            cur.next = tmp;
            cur = tmp;
            left = left.next;
        }
        if (carry != 0) {
            cur.next = new ListNode(carry);
        }
        return head.next;
    }

}
